import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import {conventEnumValueToString} from '../utils';
import {Link} from 'react-router-dom';
import routes from './routes';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';
import {abandonData} from './api';
import {baseDataStatus, faultType} from '../Enum';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }

    render() {
        const {permissions} = this.props;
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };

        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '编号',
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder
        }, {
            title: formatMessage({
                id: 'tablePanel.column.brandCode',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandCode',
            render: (text, r) => `(${r.brandCode})${r.brandName}`
        }, {
            title: formatMessage({
                id: 'tablePanel.column.faultType',
                defaultMessage: '故障类型'
            }),
            dataIndex: 'faultType',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'faultType' && this.props.sortedOrder,
            render: text => conventEnumValueToString(faultType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dutyUnitCode',
                defaultMessage: '责任单位'
            }),
            dataIndex: 'dutyUnitCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dutyUnitCode' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.supplierCode',
                defaultMessage: '供应商'
            }),
            dataIndex: 'supplierCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'supplierCode' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partCode',
                defaultMessage: '判定零件编号'
            }),
            dataIndex: 'partCode'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.transmission',
                defaultMessage: '判定变速箱型号'
            }),
            dataIndex: 'transmission'
        }, {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态',
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(baseDataStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
            render: text => <Ellipsis tooltip fullWidthRecognition length={20}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <Link key="update" to={routes.update.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.update',
                            defaultMessage: '编辑'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                }, {
                    id: PERMISSION.abandon,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="abandon"
                            placement="topLeft"
                            onConfirm={this.onClickAbandonBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.abandon',
                                defaultMessage: '是否确认作废？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.abandon',
                                    defaultMessage: '作废'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        return (
            <Table
                className={'white-space-nowrap'}
                columns={columns}
                dataSource={this.props.data}
                loading={this.props.loading || this.state.loading}
                onChange={this.onChangeSort}
                pagination={pagination}
                rowKey="id"
                locale={locale}
                {...TABLE}/>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    refreshListData: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


